import React, { useRef } from 'react';
import classNames from 'classnames';
import { useDraggable } from '@dnd-kit/core';

import { Header } from './Header';
import { MAX_DRAWER_HEIGHT_PERCENT } from '../../internals/constants';
import styles from './index.less';

interface Props {
  children: React.ReactNode;
  expanded?: boolean;
  header: React.ReactNode;
  setContentScrollTop?: (contentScrollTop: number) => void;
}

export function Sheet({ children, header, setContentScrollTop }: Props) {
  const contentRef = useRef<HTMLDivElement>(null);

  contentRef.current?.addEventListener('scroll', (e: Event) => {
    const contentScrollTop = contentRef.current?.scrollTop || 0;
    setContentScrollTop?.(contentScrollTop);
  });

  const { attributes, isDragging, listeners, transform, setNodeRef } = useDraggable({
    id: 'header',
  });

  return (
    <div
      className={classNames(styles.Sheet, {
        [styles.dragging]: isDragging,
      })}
      style={
        {
          '--max-height': `${MAX_DRAWER_HEIGHT_PERCENT * 100}vh`,
          '--transform': transform ? `${transform.y}px` : undefined,
        } as React.CSSProperties
      }
    >
      <Header ref={setNodeRef} {...attributes} {...listeners}>
        {header}
      </Header>
      <div className={styles.Content} ref={contentRef}>
        {children}
      </div>
    </div>
  );
}
